import { BasicLayout, RouteView } from '@/layouts'
export function generateIndexRouter (data) {
  const indexRouter = [
    {
      path: '/',
      name: 'dashboard',
      component: BasicLayout,
      meta: {
        title: '首页'
      },
      redirect: '/dashboard/analysis',
      children: [
        {
          path: 'dashboard',
          name: 'dashboard',
          redirect: '/dashboard/analysis',
          component: RouteView,
          meta: {
            title: '首页',
            keepAlive: true,
            url: '/dashboard/analysis',
            icon: 'home',
            componentName: 'RouteView'
          },
          children: [
            {
              hidden: true,
              path: '/dashboard/analysis',
              name: 'dashboard-Analysis',
              component: (resolve) => require(['@/views/dashboard/MyAnalysis.vue'], resolve),
              meta: {
                id: 1,
                title: '首页',
                icon: 'home',
                url: '/dashboard/analysis',
                keepAlive: true,
                componentName: 'Analysis'
              }
            }
          ]
        },
        ...generateChildRouters(data),
      ]
    },
    {
      path: '*',
      redirect: '/404',
      hidden: true
    }
  ]
  return indexRouter
}

// 生成嵌套路由（子路由）
function generateChildRouters (data) {
  const routers = []
  for (var item of data) {
    let component = ''
    if (item.component.indexOf('layouts') >= 0) {
      component = item.component
    } else {
      component = 'views/' + item.component
    }
    const componentName = component.split('/').pop()
    /* eslint-disable */
    if (isURL(item.meta.url)) {
      item.meta.url = (item.meta.url || '').replace(/{{([^}}]+)?}}/g, process.env.VUE_APP_PAGE_BASE_URL)
    }
    const menu = {
      path: item.path,
      name: item.name,
      redirect: item.redirect,
      component: (resolve) => require(['@/' + component + '.vue'], resolve),
      hidden: item.hidden,
      // component:()=> import(`@/views/${item.component}.vue`),
      meta: {
        id: item.id,
        title: item.meta.title,
        icon: item.meta.icon,
        url: item.meta.url,
        keepAlive: item.meta.keepAlive,
        permissionList: item.meta.permissionList,
        componentName
      }
    }
    if (item.alwaysShow) {
      menu.alwaysShow = true
    }
    if (item.children && item.children.length > 0) {
      menu.children = [...generateChildRouters(item.children)]
    }
    routers.push(menu)
  }
  return routers
}

function isURL (s) {
  return /{{([^}}]+)?}}/g.test(s)
}